package main

import (
	"flag"
	"fmt"
	"gitee.com/A1001574000/feedback-rpc/feedback"
	"gitee.com/A1001574000/feedback-rpc/internal/config"
	"gitee.com/A1001574000/feedback-rpc/internal/server"
	"gitee.com/A1001574000/feedback-rpc/internal/svc"
	"gitee.com/A1001574000/feedback-rpc/model"
	"github.com/BarnabyCharles/frame/app"
	config2 "github.com/BarnabyCharles/frame/config"
	"github.com/BarnabyCharles/frame/databases/mysql"
	"github.com/ghodss/yaml"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"log"
)

func main() {
	flag.Parse()
	var c config.Config
	viper, err := config2.InitViper("etc", "./etc/feedback.yaml", "yaml")
	if err != nil {
		log.Println(err)
		return
	}
	err = app.Init(
		viper.GetString("Nacos.serverName"),
		viper.GetString("Nacos.group"),
		viper.GetString("Nacos.namespaceId"),
		viper.GetString("Nacos.host"),
		viper.GetInt("Nacos.port"), "mysql")
	if err != nil {
		log.Println(err)
		return
	}
	nacosConfig, err := config2.GetNacosConfig(viper.GetString("Nacos.ServerName"), viper.GetString("Nacos.group"))
	if err != nil {
		return
	}
	yaml.Unmarshal([]byte(nacosConfig), &c)
	ctx := svc.NewServiceContext(c)

	err = model.Migrate()
	if err != nil {
		panic(err)
	}
	db, err := mysql.DB.DB()
	if err != nil {
		return
	}
	defer db.Close()
	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		feedback.RegisterFeedbackServer(grpcServer, server.NewFeedbackServer(ctx))

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
